package com.cj.image.service;

import cn.hutool.core.io.FileUtil;
import com.cj.image.bean.ImageTableBean;
import com.cj.image.bean.TaskInfoBean;
import com.cj.image.mapper.ImageMapper;
import com.cj.image.mapper.TaskInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.List;

@Service
@Slf4j
public class FileService {
    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private TaskInfoMapper taskInfoMapper;

    @Transactional
    @Async
    public  void insertImageByFilePath(String filePath){
        List<TaskInfoBean> taskInfoBeans = taskInfoMapper.selectByStatus("1");
        if(taskInfoBeans.size()>0){
            throw new RuntimeException("有任务正在运行");
        }else{
            TaskInfoBean taskInfoBean = new TaskInfoBean(null, "1");
            taskInfoMapper.insertTaskInfo(taskInfoBean);
            List<File> files = FileUtil.loopFiles(filePath);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
            for (File file : files) {
                Date lastModifiedDate = new Date(file.lastModified());
                String month = dateFormat.format(lastModifiedDate);
                ImageTableBean imageTableBean = new ImageTableBean(null, file.getName(), file.getPath(), month, lastModifiedDate);
//                imageMapper.deleteAllExceptMinId(file.getName(), file.getPath());
//                ImageTableBean imageTableBean1 = imageMapper.selectByFileNameAndPath(file.getName(), file.getPath());
//                imageTableBean.setId(imageTableBean1.getId());
//                imageMapper.insertOrUpdateImageTable(imageTableBean);
                imageMapper.insertOrUpdateImageTable(imageTableBean);
            }
            taskInfoBean.setTaskStatus("0");
            taskInfoMapper.updateTaskInfo(taskInfoBean);
        }
    }

}
